'use strict';

/**
 * @ngdoc function
 * @name nodeApp.controller:IndexCtrl
 * @description
 * # IndexCtrl
 * Controller of the nodeApp
 */
app.controller('IndexCtrl', function ($scope, $http, $stateParams, $state,$location) {
  $scope.selected = ($stateParams.tag && $stateParams.tag.split('-')) || [];
  $scope.category = $stateParams.cate || 'all';
  $scope.page = $stateParams.page || 1;

  $scope.addTag = function (i) {
    $scope.selected.push($scope.tags[i]);
    $scope.tags.splice(i, 1);
    $scope.page = 1;
    reload();
  };
  $scope.removeTag = function (i) {
    $scope.tags.push($scope.selected[i]);
    $scope.selected.splice(i, 1);
    $scope.page = 1;
    reload();
  };
  $scope.czCate = function (i, f) {
    $scope.category = $scope.categories[i];
    if (f) $scope.category = 'all';
    $scope.page = 1;
    reload();
  };

  $scope.go = function (i) {
    if (typeof i == 'number') $scope.page = i;
    else if (i == 'up') $scope.page = $scope.page - 1;
    else if (i == 'down') $scope.page = $scope.page-0 + 1;
    reload();
  };
  function reload() {
    $location.url($scope.category+'/'+$scope.selected.join('-')+'/'+$scope.page);
    load();
  }
  function load(){

    $http.post('/page/' + $scope.page, {
      tags: $scope.selected,
      category: $scope.category
    }).then(function (res) {
      $scope.sections = res.data.article;
      $scope.maxPage = res.data.maxPage;
      $scope.$broadcast('finish-reload');
    });
  }

  $http.get('/tag').then(function (res) {
    $scope.tags = res.data;
  });
  $http.get('/category').then(function (res) {
    $scope.categories = res.data;
  });

  load();

});
